package com.jason.lightreader.aop;

import com.jason.lightreader.response.Result;
import com.jason.lightreader.service.ScoreService;
import com.jason.lightreader.util.SecurityContext;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//对用户行为进行评分
@Aspect
@Component
public class UserBehaviorScoreAdvice {

    @Autowired
    private ScoreService scoreService;

    @Pointcut("execution(* com.jason.lightreader.service.ArticleService.addOrRemoveToMyCollection(..))")
    private void CollectedPt() {
    }

    @Pointcut("execution(* com.jason.lightreader.service.ArticleService.getArticleDetails(..))")
    private void getArticlePt() {
    }

    //收藏文章分数计算
    @AfterReturning(pointcut = "CollectedPt()",
            returning = "result")
    public void afterCollected(JoinPoint joinPoint, Result result) {
        //如果收藏成功加3分
        if (result.getCode() == 200) {
            Integer articleID = (Integer) joinPoint.getArgs()[0];
            if (result.getData().equals(true)) {
                scoreService.AddPoints(articleID, 3);
            } else {
                //否则扣3分
                scoreService.DecPoints(articleID, 3);
            }
        }
    }

    //查看文章分数计算
    @AfterReturning(pointcut = "getArticlePt()",
            returning = "result")
    public void afterReading(JoinPoint joinPoint, Result result) {
        if (!SecurityContext.isLogin()) {
            return;
        }
        //阅读成功加1分
        if (result.getCode() == 200) {
            Integer articleID = (Integer) joinPoint.getArgs()[0];
            scoreService.AddPoints(articleID, 1);
        }
    }
}
